package com.edu.listener;

import com.api.order.OrderClient;
import com.edu.service.IPayService;
import com.edu.vo.Result;
import com.edu.websocket.Websocket;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(consumerGroup = "edu-pay-consumer",
    topic = "order",selectorExpression = "order-delay",
    consumeMode = ConsumeMode.CONCURRENTLY,
    messageModel = MessageModel.CLUSTERING)
public class ConsumerListener implements RocketMQListener<String> {

    @Autowired
    private IPayService payService;

    @Autowired
    private OrderClient orderClient;

    @Override
    public void onMessage(String orderId) {

        try {
            //判断订单的支付状态
            Result result = payService.status(orderId);

            if ("NOTPAY".equals(result.getData())){
                //超时未支付，
                //关闭订单
                Result closeRes = payService.close(orderId);
                if (closeRes.isSuccess()){
                    //修改数据库订单状态
                    orderClient.releaseOrder(orderId);
                }
                //通知前端
                Websocket.sendMessageToClient(orderId,"fail");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
